<?php
/**
 * Created by PhpStorm.
 * User: server
 * Date: 2019/5/22
 * Time: 15:53
 */

namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path'), EXT);

use app\admin\Controller;
use think\Db;
use think\Config;
use think\Request;
use think\Validate;

class HotelSettlement extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {

        $data = input();
        $map = [];

        $map['is_apply_settlement'] = 1;
        $map['is_settlement'] = 0;
        if ($this::$isdelete) {
            $map['ha.isdelete'] = 1;
        } else {
            $map['ha.isdelete'] = 0;
        }
        if (!empty($data['hotel_name'])) {
            $map['h.hotel_name'] = ['like', "%{$data['hotel_name']}%"];
        }
        if (!empty($data['group_id'])) {
            $map['ha.group_id'] = ['=', $data['group_id']];
        }
        if (!empty($data['title'])) {
            $map['r.title'] = ['like', "%{$data['title']}%"];
        }
        if (!empty($data['realname'])) {
            $map['au.realname'] = ['like', "%{$data['realname']}%"];
        }
        if (!empty($data['account_name'])) {
            $map['ha.account_name'] = ['like', "%{$data['account_name']}%"];
        }
        if (!empty($data['account'])) {
            $map['ha.account'] = ['like', "%{$data['account']}%"];
        }
        if (!empty($data['account_bank'])) {
            $map['ha.account_bank'] = ['like', "%{$data['account_bank']}%"];
        }
        if (!empty($data['room_name'])) {
            $map['hrt.room_name'] = ['like', "%{$data['room_name']}%"];
        }
        if ($data['check_in_date'] && $data['check_in_date2']) {
            $map['ha.check_in_date'] = array("between", [strtotime($data['check_in_date'] . " 00:00:00"), strtotime($data['check_in_date2'] . " 23:59:59")]);
        } else {
            if ($data['check_in_date']) {
                $map['ha.check_in_date'] = array("between", [strtotime($data['check_in_date'] . " 00:00:00"), strtotime($data['check_in_date'] . " 23:59:59")]);
            }
            if ($data['check_in_date2']) {
                $map['ha.check_in_date'] = array("between", [strtotime($data['check_in_date2'] . " 00:00:00"), strtotime($data['check_in_date2'] . " 23:59:59")]);
            }
        }

        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");

        $list = Db::name('hotel_accommodation')
            ->alias('ha')
            ->join('tp_hotel h', 'ha.hotel_id=h.id', 'left')
            ->join('tp_route r', 'ha.route_id=r.id', 'left')
            ->join('tp_admin_user au', 'ha.driver_user_id=au.id', 'left')
            ->join('tp_hotel_room_type hrt', 'ha.hotel_room_type=hrt.id', 'left')
            ->field('ha.*,h.hotel_name,r.title,au.realname,hrt.room_name')
            ->order('id desc')
            ->where($map)
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        $new_list = $list->toArray()['data'];

        foreach ($new_list as $k => $v) {
            $temp = explode(',', $v['order_travel_ids']);
            $order_travel_names = [];
            foreach ($temp as $k2 => $v2) {
                $order_travel_names[] = Db::name('order_traveler')
                    ->where('id', $v2)
                    ->value('name');
            }
            $new_list[$k]['order_travel_names'] = implode(',', $order_travel_names);
        }

        $this->view->assign('list', $new_list);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        return $this->view->fetch();
    }

    /**
     * 电子表格
     * @return mixed
     */
    public function get_excel(Request $request)
    {
        $data = input();
        ini_set('max_execution_time', 3600);//1小时
        ini_set('memory_limit', '500M');
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel, 'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l + 65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j] . $letter[$k];
            }
        }
        $tableHeader = ['酒店名称', '派车单号', '路线名称', '司机', '申请日期', '客人', '入住日期', '账户名称', '账号', '开户行', '房型', '房型单价', '订金','尾款', '总价', '备注', '房型使用量'];
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++) {
            $export_sheet->setCellValue("$letter[$i]1", "$tableHeader[$i]");
            $export_sheet->getColumnDimension("$letter[$i]")->setWidth(20);
        }
        $map = array();

        //选择导出数据
        if ($data['id']) {
            $id = implode($data['id'], ',');
            $map['ha.id'] = ['in', $id];
        }

        $map['is_apply_settlement'] = 1;
        $map['is_settlement'] = 0;
        if ($this::$isdelete) {
            $map['ha.isdelete'] = 1;
        } else {
            $map['ha.isdelete'] = 0;
        }
        if (!empty($data['hotel_name'])) {
            $map['h.hotel_name'] = ['like', "%{$data['hotel_name']}%"];
        }
        if (!empty($data['group_id'])) {
            $map['ha.group_id'] = ['=', $data['group_id']];
        }
        if (!empty($data['title'])) {
            $map['r.title'] = ['like', "%{$data['title']}%"];
        }
        if (!empty($data['realname'])) {
            $map['au.realname'] = ['like', "%{$data['realname']}%"];
        }
        if (!empty($data['account_name'])) {
            $map['ha.account_name'] = ['like', "%{$data['account_name']}%"];
        }
        if (!empty($data['account'])) {
            $map['ha.account'] = ['like', "%{$data['account']}%"];
        }
        if (!empty($data['account_bank'])) {
            $map['ha.account_bank'] = ['like', "%{$data['account_bank']}%"];
        }
        if (!empty($data['room_name'])) {
            $map['hrt.room_name'] = ['like', "%{$data['room_name']}%"];
        }
        if ($data['check_in_date'] && $data['check_in_date2']) {
            $map['ha.check_in_date'] = array("between", [strtotime($data['check_in_date'] . " 00:00:00"), strtotime($data['check_in_date2'] . " 23:59:59")]);
        } else {
            if ($data['check_in_date']) {
                $map['ha.check_in_date'] = array("between", [strtotime($data['check_in_date'] . " 00:00:00"), strtotime($data['check_in_date'] . " 23:59:59")]);
            }
            if ($data['check_in_date2']) {
                $map['ha.check_in_date'] = array("between", [strtotime($data['check_in_date2'] . " 00:00:00"), strtotime($data['check_in_date2'] . " 23:59:59")]);
            }
        }

        $list = Db::name('hotel_accommodation')
            ->alias('ha')
            ->join('tp_hotel h', 'ha.hotel_id=h.id', 'left')
            ->join('tp_route r', 'ha.route_id=r.id', 'left')
            ->join('tp_admin_user au', 'ha.driver_user_id=au.id', 'left')
            ->join('tp_hotel_room_type hrt', 'ha.hotel_room_type=hrt.id', 'left')
            ->field('h.hotel_name,ha.group_id,r.title,au.realname,ha.apply_time,ha.order_travel_ids,ha.check_in_date,ha.account_name,ha.account,ha.account_bank,hrt.room_name,ha.unit_price,ha.subscription,ha.balance_payment,ha.total_price,ha.remark,ha.end_date,ha.check_in_date')
            ->order('ha.id desc')
            ->where($map)
            ->select();

        foreach ($list as $k => $v) {
            $temp = explode(',', $v['order_travel_ids']);
            $order_travel_names = [];
            foreach ($temp as $k2 => $v2) {
                $order_travel_names[] = Db::name('order_traveler')
                    ->where('id', $v2)
                    ->value('name');
            }
            $list[$k]['order_travel_ids'] = implode(',', $order_travel_names);

            $list[$k]['usage'] = ($v['end_date'] - $v['check_in_date']) / 86400;

            if ($v['apply_time']) {
                $list[$k]['apply_time'] = date('Y-m-d H:i:s', $v['apply_time']);
            }
            if ($v['check_in_date']) {
                $list[$k]['check_in_date'] = date('Y-m-d H:i:s', $v['check_in_date']);
            }

            unset($list[$k]['end_date']);

        }

//        halt($list);
        if (!empty($list)) {
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk => $tv) {
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++) {
                    $export_sheet->setCellValue("$letter[$i]" . $tk, $tv[$tableKey[$i]]);
                }
            }
        }
        //定义table键
        if (!empty($list)) {
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk => $tv) {
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++) {
                    $export_sheet->setCellValue("$letter[$i]" . $tk, $tv[$tableKey[$i]]);
                }
            }
        }
        $fileName = date('YmdHis', time()) . "酒店结算-酒店结算数据.xls";
        $fileName = iconv('utf-8', 'gb2312', $fileName);
        ob_end_clean();
        if ($request->isGet()) {
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename=' . $fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        } else {
            // 保存文件到服务器上
            $path = ROOT_PATH . "public/excel";
            // 判断文件是否存在
            if (!file_exists($path)) {
                mkdir($path, 0777, true);
            }
            $fileName = iconv('gb2312', 'utf-8', $fileName);
            $file = $path . "/{$fileName}";
            $writer->save($file);
            $url = $request->domain() . "/excel/{$fileName}";
            return ajax_return_adv($url, '', '', '', '', '', 5);
        }
    }

    /**
     * 确认结算（结算成功）
     * @return mixed
     * @author 李锐志
     */
    public function confirm_settlement()
    {
        $data = input();


        if ($this->request->isAjax()) {
            $rule = [
                'id' => 'require',
                'settlement_mode' => 'require',
            ];
            $msg = [
                'id.require' => '参数错误',
                'settlement_mode.require' => '结算方式不能为空',
            ];

            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                return ajax_return_error($validate->getError());
            }

            $hotel_accommodation = Db::name('hotel_accommodation')->where('id', $data['id'])->find();

            //判断申请状态
            if ($hotel_accommodation['is_apply_settlement'] != '1') {
                return ajax_return_error('请先申请结算');
            }

            if ($hotel_accommodation['is_settlement'] == '1') {
                return ajax_return_error('该申请已结算');
            }

            if ($hotel_accommodation['is_complete'] == '0') {
                return ajax_return_error('住宿未完成');
            }

            if ($hotel_accommodation['driver_user_id']) {
                //开启事务
                Db::startTrans();
                try {
                    $data['settlement_time'] = time();
                    $data['is_apply_settlement'] = 0;
                    $data['is_settlement'] = 1;
                    $data['settlement_money'] = $hotel_accommodation['total_price'] - $hotel_accommodation['subscription'];

                    $result = Db::name('hotel_accommodation')
                        ->where('id', $data['id'])
                        ->strict(false)
                        ->update($data);

                    if ($result) {
                        return ajax_return_adv('结算成功');
                    }
                } catch (\Exception $e) {
                    Db::rollback();
                    return ajax_return_adv_error($e->getMessage());
                }
            } else {
                return ajax_return_error('未分配司导');
            }

        } else {

            $result = Db::name('hotel_accommodation')
                ->alias('ha')
                ->join('tp_hotel h', 'ha.hotel_id=h.id', 'left')
                ->join('tp_route r', 'ha.route_id=r.id', 'left')
                ->join('tp_admin_user au', 'ha.driver_user_id=au.id', 'left')
                ->join('tp_hotel_room_type hrt', 'ha.hotel_room_type=hrt.id', 'left')
                ->field('ha.*,h.hotel_name,r.title,au.realname,hrt.room_name')
                ->where('ha.id', $data['id'])
                ->find();

            $this->view->assign('vo', $result);
            return $this->view->fetch();
        }
    }

    /**
     * 批量结算（结算成功）
     * @return mixed
     * @author 颜东淦
     */
    public function batch_settlement()
    {
        $data = input();

        if (!isset($data['id'])) {
            return ajax_return_adv_error('没有选择派车单，请重试');
        }

        $success = 0;
        $error = 0;
        $error_id = [];

        foreach ($data['id'] as $k => $v) {
            $hotel_accommodation = Db::name('hotel_accommodation')->where('id', $v)->find();

            //判断申请状态
            if ($hotel_accommodation['is_apply_settlement'] != '1') {
                $error += 1;
                $error_id[] = $hotel_accommodation['group_id'];
            }

            if ($hotel_accommodation['is_settlement'] == '1') {
                $error += 1;
                $error_id[] = $hotel_accommodation['group_id'];
            }

            if ($hotel_accommodation['is_complete'] == '0') {
                $error += 1;
                $error_id[] = $hotel_accommodation['group_id'];
            }

            if ($hotel_accommodation['driver_user_id']) {
                //开启事务
                Db::startTrans();
                try {
                    $update['settlement_time'] = time();
                    $update['is_apply_settlement'] = 0;
                    $update['is_settlement'] = 1;
                    $update['settlement_money'] = $hotel_accommodation['total_price'];
                    $update['settlement_mode'] = $data['settlement_mode'];

                    $result = Db::name('hotel_accommodation')
                        ->where('id', $v)
                        ->strict(false)
                        ->update($update);

                    if ($result) {
                        $success += 1;
                    }
                } catch (\Exception $e) {
                    Db::rollback();
                    $error += 1;
                    $error_id[] = $hotel_accommodation['group_id'];
                }
            } else {
                $error += 1;
                $error_id[] = $hotel_accommodation['group_id'];
            }
        }
        if (count($error_id) === 0) {
            $msg = '成功结算：' . $success . '条。失败结算' . $error . "条。";
        } else {
            $temp = implode(',', $error_id);
            $msg = '成功结算：' . $success . '条。失败结算' . $error . "条。失败的派车单ID为：" . $temp . "。";
        }
        return ajax_return_adv($msg);
    }

    /**
     * 拒绝结算
     * @author 李锐志
     */
    public function refuse_settlement()
    {
        $data = input();

        if ($this->request->isAjax()) {

            $rule = [
                'id' => 'require',
                'reject_remark' => 'require',
            ];
            $msg = [
                'id.require' => '参数错误',
                'reject_remark.require' => '拒绝原因不能为空',
            ];

            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                return ajax_return_error($validate->getError());
            }

            $hotel_accommodation = Db::name('hotel_accommodation')->where('id', $data['id'])->find();

            //判断派车单状态
            if ($hotel_accommodation['is_apply_settlement'] != '1') {
                return ajax_return_error('请先申请结算');
            }

            if ($hotel_accommodation['is_settlement'] == '1') {
                return ajax_return_error('该申请已结算');
            }

            if ($hotel_accommodation['is_complete'] == '0') {
                return ajax_return_error('住宿未完成');
            }

            if ($hotel_accommodation['driver_user_id']) {

                //开启事务
                Db::startTrans();
                try {
                    $data['is_settlement'] = 0;
                    $data['is_apply_settlement'] = 0;
                    $data['reject_time'] = time();
                    $data['is_reject'] = 1;

                    $result = Db::name('hotel_accommodation')
                        ->where('id', $data['id'])
                        ->strict(false)
                        ->update($data);

                    if ($result) {
                        return ajax_return_adv('驳回成功');
                    }
                } catch (\Exception $e) {
                    Db::rollback();
                    return ajax_return_adv_error($e->getMessage());
                }
            } else {
                return ajax_return_error('未分配司导');
            }
        } else {

            $result = Db::name('hotel_accommodation')
                ->alias('ha')
                ->join('tp_hotel h', 'ha.hotel_id=h.id', 'left')
                ->join('tp_route r', 'ha.route_id=r.id', 'left')
                ->join('tp_admin_user au', 'ha.driver_user_id=au.id', 'left')
                ->join('tp_hotel_room_type hrt', 'ha.hotel_room_type=hrt.id', 'left')
                ->field('ha.*,h.hotel_name,r.title,au.realname,hrt.room_name')
                ->where('ha.id', $data['id'])
                ->find();

            $this->view->assign('vo', $result);
            return $this->view->fetch();
        }
    }

    /**
     * 批量驳回
     * @return mixed
     * @author 颜东淦
     */
    public function batch_refuse()
    {
        $data = input();

        if (!isset($data['id'])) {
            return ajax_return_adv_error('没有选择派车单，请重试');
        }

        $success = 0;
        $error = 0;
        $error_id = [];

        foreach ($data['id'] as $k => $v) {
            $hotel_accommodation = Db::name('hotel_accommodation')->where('id', $v)->find();

            //判断派车单状态
            if ($hotel_accommodation['is_apply_settlement'] != '1') {
                $error += 1;
                $error_id[] = $hotel_accommodation['group_id'];
            }

            if ($hotel_accommodation['is_settlement'] == '1') {
                $error += 1;
                $error_id[] = $hotel_accommodation['group_id'];
            }

            if ($hotel_accommodation['is_complete'] == '0') {
                $error += 1;
                $error_id[] = $hotel_accommodation['group_id'];
            }

            if ($hotel_accommodation['driver_user_id']) {

                //开启事务
                Db::startTrans();
                try {
                    $data['is_settlement'] = 0;
                    $data['is_apply_settlement'] = 0;
                    $data['reject_time'] = time();
                    $data['is_reject'] = 1;

                    $result = Db::name('hotel_accommodation')
                        ->where('id', $v)
                        ->strict(false)
                        ->update($data);

                    if ($result) {
                        $success += 1;
                    }
                } catch (\Exception $e) {
                    Db::rollback();
                    $error += 1;
                    $error_id[] = $hotel_accommodation['group_id'];
                }
            } else {
                $error += 1;
                $error_id[] = $hotel_accommodation['group_id'];
            }
        }
        if (count($error_id) === 0) {
            $msg = '成功驳回：' . $success . '条。失败驳回' . $error . "条。";
        } else {
            $temp = implode(',', $error_id);
            $msg = '成功驳回：' . $success . '条。失败驳回' . $error . "条。失败的派车单ID为：" . $temp . "。";
        }
        return ajax_return_adv($msg);
    }
}